<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>监听器验证用户名可用</title>
</head>
<body>

<div id="app">
  <div>
    <label for="username"> 用户名：
      <input type="text" id="username" v-model.lazy="username">
    </label>
    <span v-text="tip"></span>
  </div>
</div>

<script src="../lib/vue.js"></script>
<script>
  let vm = new Vue({
    el: '#app',
    data: {
      username: '',
      tip: '',
      existName: ['Jim', 'Tom', 'Cate']
    },
    watch: {
      username(val) {
        if (val.length === 0) {
          this.tip = ''
          return;
        }
        this.checkName(val);
        this.tip = '正在验证...'
      }
    },
    methods: {
      checkName(username) {
        let that = this;
        setTimeout(function () {
          let indexOf = that.existName.indexOf(username);
          if (indexOf >= 0) {
            that.tip = '该用户名已被占用'
          } else {
            that.tip = '该用户名可用'
          }
        }, 1000)
      }
    }
  })
</script>

</body>
</html>